// pages/student/recognition.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    fileUrl: '',
    way: false,
    isAuth: false,
    src: '',
    img: false,
    facesComparisonCode:0,
    uid: wx.getStorageSync('userinfo').uid,
    imgPath: '',
    direction: 'front',
    cid: '',
    navConfig: {
      title: '确认框',
      type: 1,
      config: {
        show: true,
        type: 'confirm',
        showTitle: true,
        title: '标题',
        content: '这个是确认框',
        confirmText: '确定',
        confirmColor: '#3683d6',
        cancelText: '取消',
        cancelColor: '#999'
      },
    },

    videostatus: false,
    sum: 0,
    errorflag: false,

    currentConf2: {},
    currentConfConfig: {
      show: true,
      animation: 'show',
      zIndex: 99,
      contentAlign: 'bottom',
      locked: false,
    },
    signresult: []
  },

  onMessage() {
    this.setData({
      show: true,
      type: 'primary',
      duration: 1500,
      content: '拍摄时不要移动太快！'
    });
  },

  changerotate() {
    var direction = this.data.direction == 'back' ? 'front' : 'back'
    this.setData({
      direction: direction
    })
  },

  changeway() {
    var w = this.data.way
    this.setData({
      way: !w,
      img: false
    })
  },
  // 打开授权设置界面
  openSetting() {
    const _this = this
    let promise = new Promise((resolve, reject) => {
      wx.showModal({
        title: '授权',
        content: '请先授权获取摄像头权限',
        success(res) {
          if (res.confirm) {
            wx.openSetting({
              success(res) {
                if (res.authSetting['scope.camera']) { // 用户打开了授权开关
                  resolve(true)
                } else { // 用户没有打开授权开关， 继续打开设置页面
                  _this.openSetting().then(res => {
                    resolve(true)
                  })
                }
              },
              fail(res) {}
            })
          } else if (res.cancel) {
            _this.openSetting().then(res => {
              resolve(true)
            })
          }
        }
      })
    })
    return promise;
  },

  // 显示Popup
  onShowPopupTap() {
    const config = this.data.currentConfConfig;
    this.setData({
      currentConf2: config
    });
  },

  startVideo() {
    this.onMessage()
    var that = this
    var vs = this.data.videostatus
    this.setData({
      videostatus: !vs,
      sum: 0
    })
    this.track()
  },

  track() {
    if (this.data.videostatus) {
      this.takePhoto2()
    }
  },

  takePhoto2() {
    var sum = this.data.sum
    const ctx = wx.createCameraContext()
    var result = this.data.signresult
    ctx.takePhoto({
      quality: 'high',
      success: async (res) => {
        this.setData({
          src: res.tempImagePath,
        })
        var that = this
        wx.uploadFile({
          url: 'https://www.xqzjgsu.xyz/fss/auth/videoFacesComparison',
          filePath: that.data.src,
          name: 'file',
          header: {
            'content-type': 'multipart/form-data',
            'Authorization': 'Bearar ' + wx.getStorageSync('token')
          },
          formData: {
            'cid': that.data.cid,
            'lid': that.data.lid,
          },
          success: async function (res) {
            var datas = JSON.parse(res.data)
            that.setData({
              facesComparisonCode: datas.code
            })
            if (datas.code == 200) {
              if (datas.data.length != 0) {
                sum += datas.data.length
                var result1 = datas.data.concat(result)
                that.setData({
                  signresult: result1,
                  sum
                })
              }
            }else{
              wx.showToast({
                icon: 'none',
                title: datas.message,
              })
            }
            that.track()
          }
        })
      }
    })
  },

  finishVideo() {
    var vs = this.data.videostatus
    var sum = this.data.sum
    this.setData({
      videostatus: !vs
    })
    clearInterval(this.data.timer)
    var navTemp = this.data.navConfig
    if (sum == 0) {
      navTemp.config.content = "此次录像无一人签到成功，请重试！"
      this.setData({
        navConfig: navTemp,
        errorflag: true
      })
      this.onShowDioTap()
    } else {
      navTemp.config.content = "多人签到成功，可在底部查看结果"
      this.setData({
        navConfig: navTemp
      })
      this.onShowDioTap()
    }
  },

  takePhoto() {
    const ctx = wx.createCameraContext()
    ctx.takePhoto({
      quality: 'high',
      success: (res) => {
        this.setData({
          src: res.tempImagePath,
          img: true
        })
        wx.previewImage({
          current: res.tempImagePath, // 当前显示图片的http链接
          urls: [res.tempImagePath] // 需要预览的图片http链接列表
        })
      }
    })
  },
  secondTakePhoto() {
    this.setData({
      src: '',
      img: false
    })
  },
  finish: function () {
    //显示等待框
    wx.showLoading({
      title: '识别中...',
    })
    var that = this
    wx.uploadFile({
      url: 'https://www.xqzjgsu.xyz/fss/auth/facesComparison',
      filePath: that.data.src,
      name: 'file',
      header: {
        'content-type': 'multipart/form-data',
        'Authorization': 'Bearar ' + wx.getStorageSync('token')
      },
      formData: {
        'cid': that.data.cid,
        'lid': that.data.lid,
      },
      success: async function (res) {
        var result = JSON.parse(res.data)
        var navTemp = that.data.navConfig
        if (result.code == 500) {
          wx.showToast({
            icon: 'none',
            title: result.message,
          })
        } else if (result.code == 200) {
          var number = result.data.length
          if (number == 0) {
            navTemp.config.content = '图中的所有用户都已成功签到，请勿重复签到，是否回到首页，查看具体结果？'
          } else {
            navTemp.config.content = '成功签到' + number + '人，是否回到首页，查看具体结果？'
          }
          that.setData({
            facesComparisonCode: result.code,
            navConfig: navTemp
          })
          that.onShowDioTap()
        } else {
          navTemp.config.content = result.message
          that.setData({
            navConfig: navTemp
          })
          that.onShowDioTap()
        }
      }
    })
    //隐藏等待框
    wx.hideLoading({
      success: (res) => {},
    })
  },

  // 确定按钮
  onConfirmTap() {
    // 拍照的是200,确认的到首页
    // 录像的是:是录像+errorflag是false
    if ((!this.data.way && this.data.facesComparisonCode == 200)) {
      wx.switchTab({
        url: '/pages/teacher/sign_home',
      })
    }

  },

  // 取消按钮
  onCancelTap() {
    wx.switchTab({
      url: '/pages/teacher/sign_home',
    })
  },

  // 显示 dio
  onShowDioTap() {
    const config = JSON.parse(JSON.stringify(this.data.navConfig.config));
    this.setData({
      currentConf: config
    });
  },



  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

    //屏幕宽度
    var sysInfo = wx.getSystemInfoSync()
    this.setData({
      windowWidth: sysInfo.windowWidth,
      cid: options.cid,
      lid: options.lid
    })
    wx.setStorageSync('cid', options.cid)
    this.setData({
      uid: wx.getStorageSync('userinfo').uid
    })
    const _this = this
    wx.getSetting({
      success: res => {
        if (res.authSetting['scope.camera']) {
          // 用户已经授权
          _this.setData({
            isAuth: true
          })
        } else {
          // 用户还没有授权，向用户发起授权请求
          wx.authorize({
            scope: 'scope.camera',
            success() { // 用户同意授权
              _this.setData({
                isAuth: true
              })
            },
            fail() { // 用户不同意授权
              _this.openSetting().then(res => {
                _this.setData({
                  isAuth: true
                })
              })
            }
          })
        }
      },
      fail: res => {}
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    wx.hideHomeButton();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})